import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import { Card, Button, Form, Input, DatePicker, Select, Tooltip, Spin } from 'antd';
import MyPageTable from '@/components/MyPageTable';
import { onTableData } from '@/utils/utils.js';
import CopyToClipboard from '@/components/CopyToClipboard';
import moment from 'moment';
import { getTimeDistance } from '@/utils/utils';
import { orderStatusMap } from "@/utils/enum";

const { RangePicker } = DatePicker;
const { Option } = Select;

@connect(({ order, loading }) => ({
  ...order, loading: false
})) @Form.create()

export default class Source extends Component {
  state = {
    current: 1, datas: {}, yunTime: getTimeDistance('month'),
  };

  componentDidMount() {
    this.props.dispatch({
      type: 'order/SourceList',
    })
  }

  onList = (pageNumber, pageSize, data = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/queryOrderByConditionExt', payload: {
        pageSize, pageNumber, ...data,
      },
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      console.log('Received values of form: ', values);
      if (values.createDate && values.createDate.length < 1) {
        values.createTimeStart = '';
        values.createTimeEnd = '';
        this.setState({
          datas: { ...values },
        }, () => {
          this.onList(1, 10, { ...values });
        },);
      } else if (values.createDate) {
        values.createTimeStart = moment(values.createDate[0]).format('YYYY-MM-DD HH:mm:ss');
        values.createTimeEnd = moment(values.createDate[1]).format('YYYY-MM-DD HH:mm:ss');
        this.setState({
          datas: { ...values },
        }, () => {
          this.onList(1, 10, { ...values });
        },);
      } else {
        this.setState({
          datas: { ...values },
        }, () => {
          this.onList(1, 10, { ...values });
        },);
      }
    });
  };

  // table 页数
  onPage = e => {
    this.setState({
      current: e.current,
    }, () => {
      this.onList(e.current, 10, this.state.datas);
    },);
  };

  // 重置
  handleReset = e => {
    this.props.form.resetFields();
    this.handleSubmit(e);
  };

  onexport = () => {
    const { yunTime } = this.state;
    const req = {
      createTimeEnd: "", createTimeStart: "", platform: "",
    }
    if (this.props.form.getFieldValue('platform')) {
      req.platform = this.props.form.getFieldValue('platform');
    }

    if (this.props.form.getFieldValue('createDate')) {
      req.createTimeEnd = moment(this.props.form.getFieldValue('createDate')[1]).format('YYYY-MM-DD HH:mm:ss');
      req.createTimeStart = moment(this.props.form.getFieldValue('createDate')[0]).format('YYYY-MM-DD HH:mm:ss');
    } else {
      req.createTimeEnd = moment(yunTime[1]).format('YYYY-MM-DD HH:mm:ss');
      req.createTimeStart = moment(yunTime[0]).format('YYYY-MM-DD HH:mm:ss');
    }

    this.props.dispatch({
      type: 'order/exportOpeAllUserOrders', payload: req,
    });
  };

  render() {
    const { allTotalExt, allListExt, sourceList, loading } = this.props;
    const paginationProps = {
      current: this.state.current,
      pageSize: 10,
      total: allTotalExt,
      showTotal: total => (<span style={{ fontSize: '14px' }}>
          <span>共{Math.ceil(total / 10)}页</span>&emsp;
        <span>共{total}条</span>
        </span>),
    };
    const columns = [{
      title: '订单编号', dataIndex: 'orderId', render: orderId => <CopyToClipboard text={orderId}/>, width: '140px',
    }, {
      title: '店铺名称', width: '150px', render: (row) => {
        return (<>{row.shopInfoDto.shopName}</>);
      },
    }, {
      title: '用户来源', width: '90px', render: (row) => {
        return (<>{row.backstageUserOrderDto.platform}</>);
      },
    }, {
      title: '商品名称', width: '200px', render: (row) => {
        return (<>{row.productInfo.productName}</>);
      },
    }, {
      title: '总租金/期数', width: '120px', render: e => {
        return <>{'￥' + e.backstageUserOrderDto.totalRentAmount} <br/> {e.backstageUserOrderDto.totalPeriods + '期'}</>;
      },
    }, {
      title: '姓名', width: '100px', render: e => {
        return <>{e.userOrderInfoDto.realName}</>;
      },
    }, {
      title: '手机号', width: '130px', render: e => {
        return <>{e.userOrderInfoDto.telephone}</>;
      },
    }, {
      title: '订单状态', width: '100px', render: e => {
        return <>{orderStatusMap[e.backstageUserOrderDto.status]}</>;
      },
    }, {
      title: '下单时间', width: '120px', render: e => {
        return <>{e.userOrderInfoDto.createTime}</>;
      },
    }, {
      title: '操作', fixed: 'right', width: '70px', align: 'center', render: e => {
        return (<div style={{ textAlign: 'center' }}>
          <a
            href={`#/Order/BeOverdue/Details?id=${e.orderId}&settlement=settlement`}
            target="_blank"
          >
            详情
          </a>
        </div>);
      },
    },];
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 }, sm: { span: 6 },
      }, wrapperCol: {
        xs: { span: 24 }, sm: { span: 16 },
      },
    };
    return (<PageHeaderWrapper>
      <Card bordered={false}>
        <Form layout="inline" onSubmit={this.handleSubmit}>
          <Form.Item label="店铺名称">
            {getFieldDecorator('shopName', {})(<Input placeholder="请输入店铺名称"/>)}
          </Form.Item>
          <Form.Item label="渠道来源">
            {getFieldDecorator('platform', {},)(<Select placeholder="渠道来源" style={{ width: 180 }} allowClear>
              {sourceList.map((item, index) => {
                return (<Option value={item} key={index}>
                  {item}
                </Option>);
              })}
            </Select>,)}
          </Form.Item>
          <Form.Item label="下单人姓名">
            {getFieldDecorator('userName', {},)(<Input allowClear placeholder="请输入下单人姓名"/>)}
          </Form.Item>
          <Form.Item label="下单人手机号">
            {getFieldDecorator('telephone', {},)(<Input allowClear placeholder="请输入下单人手机号"/>)}
          </Form.Item>
          <Form.Item label="订单编号">
            {getFieldDecorator('orderId', {})(<Input allowClear placeholder="请输入订单编号"/>)}
          </Form.Item>
          <Form.Item label="创建时间">
            {getFieldDecorator('createDate', {})(<RangePicker allowClear/>)}
          </Form.Item>
          <div>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
            <Form.Item>
              <Button htmlType="button" onClick={this.handleReset}>
                重置
              </Button>
            </Form.Item>
            <Form.Item>
              <Button onClick={this.onexport}>导出</Button>
            </Form.Item>
          </div>
        </Form>
        <Spin spinning={loading}>
          <MyPageTable
            scroll
            onPage={this.onPage}
            paginationProps={paginationProps}
            dataSource={onTableData(allListExt)}
            columns={columns}
          />
        </Spin>
      </Card>
    </PageHeaderWrapper>);
  }
}
